import 'package:mvvm_provider/base/base_state.dart';
import 'package:mvvm_provider/model/banner_model.dart';
import 'package:mvvm_provider/net/http_config.dart';
import 'package:mvvm_provider/net/ltt_https.dart';
import 'package:mvvm_provider/page/bookshelf/states/book_shelf_state.dart';
import 'package:mvvm_provider/page/home/data/model/cartoon_model.dart';
import 'package:mvvm_provider/page/home/data/repository/home_api.dart';
import 'package:mvvm_provider/page/home/data/repository/home_repository.dart';
import 'package:mvvm_provider/until/app_util.dart';
import 'package:mvvm_provider/until/string_util.dart';
import '../../../base/base_view_model.dart';
import '../../../config/handle_state.dart';
import '../../../model/response_model.dart';

class BookShelfViewModel extends BaseViewModel<BookShelfState> {
  BookShelfViewModel() : super(BookShelfState());

  /// 获取列表数据
  Future<void> getListData(bool isRefresh) async {
    int page = state.page;
    if (isRefresh) {
      page = 1;
    } else {
      page++;
    }
    if (page == 1) {
      ResponseModel? bannerResponseModel = await HomeRepository.getBannerData<List<BannerModel>>();
      state.bannerList = bannerResponseModel.data ?? [];
    }
    ResponseModel responseModel = await HomeRepository.getListData<CarDataModel>(page);
    CarDataModel carDataModel = responseModel.data;

    /// 处理页面状态
    state.netState = HandleState.handle(responseModel, successCode: 0);
    if (state.netState == NetState.dataSuccessState) {
      if (page == 1) {
        state.dataList = handleData(carDataModel.feeds ?? []);
        if (state.dataList.isEmpty) {
          state.netState = NetState.emptyDataState;
        }
      } else {
        if (AppUtil.isNotEmpty(carDataModel.feeds)) {
          state.dataList.addAll(carDataModel.feeds!);
          state.dataList = handleData(state.dataList);
        }
      }
      state.page = page;
      refreshController.refreshCompleted();
      refreshController.loadComplete();

      /// 显示没有更多数据了
      if (AppUtil.isEmpty(carDataModel.feeds)) {
        refreshController.loadNoData();
      }
    }
    notifyListeners();
  }

  /// 处理数据
  List handleData(List list) {
    for (int i = 0; i < list.length; i++) {
      CartoonModel cartoonModel = list[i];
      if (i % 3 == 0) {
        cartoonModel.crossAxisCount = 2;
      } else {
        cartoonModel.crossAxisCount = 1;
      }
    }
    return list;
  }
}
